<?php
namespace jy_area_psi;
defined('BY_JYA') or exit('error');
/*
	区域代理分红计算
	
*/
class commission extends \plugin{
	/*
		生成佣金
	*/
	function create($order){
		$isopen=intval($this->setting['isopen']);
		if(!$isopen){
			return;
		}
		$order['api_data']=is_array($order['api_data'])?$order['api_data']:json_decode($order['api_data'],true);
		$order['psi']=$order['api_data']['psi'];
		//file_put_contents(ROOT_D.'/1.txt',$order['psi']);
		if($order['psi']>0){
			$this->model('cv')->buygoods($order);
		}
		$this->model('member')->update_agent_level($order['mid']);
		$this->order=$order;
		if(!$order['pcd']){
			//获取地址
			$order['address']=json_decode($order['address'],true);
			if($order['address'] && ($order['address']['name'] || $order['address']['address'])){
				$address=$order['address'];
			}else{
				$address=pdo_get('core_address',array('uniacid'=>$_SESSION['uniacid'],'id'=>$order['addressid']),'pcd');
			}
			$address=$address['pcd'];
		}else{
			$address=$order['pcd'];
		}
        if(!is_array($address)){
            $address=json_decode($address,true);
        }
		if(!$address){
			return;
		}
		//file_put_contents(ROOT_D.'/1.txt','~2~'.$order['psi']);
		$this->commission_order=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$this->order['mid'],
			'ordersn'=>$this->order['ordersn'],
			'order_price'=>$this->order['price'],
			'commission_money'=>0,
			'order_psi'=>$this->order['psi'],
			'createtime'=>TIMESTAMP,
		);
		if($this->setting['level']>3){
			//计算镇级代理分红
			$this->street_commission($address);
		}
		if($this->setting['level']>2){
			//计算县级代理分红
			$this->district_commission($address);
		}
		if($this->setting['level']>1){
			//计算市级代理分红
			$this->city_commission($address);
		}
		$this->province_commission($address);
		//
		$fromuser=pdo_getcolumn('core_members',array('uniacid'=>$_SESSION['uniacid'],'id'=>$order['mid']),'fromuser');
		if($fromuser){
			$agent=$this->get('agent_area',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$fromuser));
			if(!$agent['level_id']){
				$agent=pdo_get('jy_weishop_member',array('merchid'=>0,'uniacid'=>$_SESSION['uniacid'],'mid'=>$fromuser));
			}
			$agent['fromuser']=$fromuser;
			$this->create_commission($agent,0,1);
			$this->create_commission($agent,0,2);
		}
		//生成分销订单
		if($this->commission_order['isarea']){
			$indata=$this->commission_order;
			unset($indata['isarea']);
			$this->insert('order',$indata);
		}
		return true;
	}
	public function province_commission($address){
		$area_code=pdo_getcolumn('core_area',array('address'=>$address['province']),'code');
		$this->commission_order['area_code']=$area_code;
		$agents=$this->getall('agent_area',array('uniacid'=>$_SESSION['uniacid'],'status'=>1,'area_code'=>$area_code));
		//file_put_contents(ROOT_D.'/1.txt',ijson_encode($agents).'~2~'.$area_code);
		if(!$agents){
			return;
		}
		if($this->order['send_status']!=14 && $this->setting['open_ordersh']){
			pdo_update('jy_weishop_order',array('send_status'=>14),array('uniacid'=>$_SESSION['uniacid'],'ordersn'=>$this->order['ordersn']));
			$this->order['send_status']=14;
		}
		foreach($agents as $agent){
			$member=$this->get('member',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$agent['mid']));
			if(!$member || $member['stop']){
				continue;
			}
			$this->create_commission($agent,1);
		}
	}
	public function city_commission($address){
		if(!$address['city']){
			return;
		}
		$area_code=pdo_getcolumn('core_area',array('address'=>$address['province'].' '.$address['city']),'code');
		$this->commission_order['area_code']=$area_code;
		$agents=$this->getall('agent_area',array('uniacid'=>$_SESSION['uniacid'],'status'=>1,'area_code'=>$area_code));
		if(!$agents){
			return;
		}
		foreach($agents as $agent){
			$member=$this->get('member',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$agent['mid']));
			if(!$member || $member['stop']){
				continue;
			}
			$this->create_commission($agent,2);
		}
	}
	public function district_commission($address){
		if(!$address['district']){
			return;
		}
		$area_code=pdo_getcolumn('core_area',array('address'=>$address['province'].' '.$address['city'].' '.$address['district']),'code');
		$this->commission_order['area_code']=$area_code;
		$agents=$this->getall('agent_area',array('uniacid'=>$_SESSION['uniacid'],'status'=>1,'area_code'=>$area_code));
		if(!$agents){
			return;
		}
		foreach($agents as $agent){
			$member=$this->get('member',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$agent['mid']));
			if(!$member || $member['stop']){
				continue;
			}
			$this->create_commission($agent,3);
		}
	}
	public function street_commission($address){
		if(!$address['street']){
			return;
		}
		$area_code=pdo_getcolumn('core_area',array('address'=>$address['province'].' '.$address['city'].' '.$address['district'].' '.$address['street']),'code');
		$this->commission_order['area_code']=$area_code;
		$agents=$this->getall('agent_area',array('uniacid'=>$_SESSION['uniacid'],'status'=>1,'area_code'=>$area_code));
		if(!$agents){
			return;
		}
		foreach($agents as $agent){
			$member=$this->get('member',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$agent['mid']));
			if(!$member || $member['stop']){
				continue;
			}
			$this->create_commission($agent,4);
		}
	}
	/*
		给指定区域代理计算分红
	*/
	function create_commission($agent,$commission_level=0,$type=4){
		if(!$agent['mid']){
			return false;
		}
			if($commission_level){
				//区域代理
				$default_level=$this->plugin_setting('default_level');
				$level_id='a'.$commission_level;
				$commission_per=$default_level['a'.$commission_level.'_rate'.$type];
			}elseif(!$agent['level_id']){
				//默认等级
				$default_level=$this->plugin_setting('default_level');
				$level_id=0;
				$commission_per=$default_level['a0'.'_rate'.$type];
			}elseif($agent['level_id']){
				//区域商直推
				$default_level=$this->plugin_setting('default_level');
				$level_id=$agent['level_id'];
				$commission_per=$default_level[$level_id.'_rate'.$type];
			}elseif($agent['level']){
				//普通直推
				$level=$this->get('level',array('shoplevelid'=>$agent['level_id'],'uniacid'=>$_SESSION['uniacid']));
				$commission_per=$level['rate'.$type];
			}
			$money=0;
			$order_psi=$this->order['jitype']?$this->commission_order['order_price']:$this->commission_order['order_psi'];
			$remark=array(
				'level_id'=>$level_id,
				'commission_level'=>$commission_level,
				'order_psi'=>$order_psi,
				'goods_commission'=>array(),
			);
			if($order_psi>0){
				$order_commission_money=$order_psi;
				if(substr($commission_per,-1)=='%'){
					$money+=($order_commission_money*substr($commission_per,0,-1))/100;
				}else{
					if($type==1){
						$money+=$commission_per*$order_psi;
					}else{
						$money+=$commission_per;
					}
				}
				$remark['order_commission']=array('order_psi'=>$order_psi,'commission_per'=>$commission_per,'commission_money'=>$order_commission_money);
			}
			$remark['commission_money']=$money;
			//file_put_contents(ROOT_D.'/1.txt',$money.'~3~'.$order_psi);
			if($money>0){
				$this->commission_order['commission_money']+=$money;
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$agent['mid'],
					'agent_id'=>$agent['fromuser'],
					'area_code'=>$agent['area_code'],
					'level'=>$commission_level,
					'ordersn'=>$this->order['ordersn'],
					'money'=>$money,
					'type'=>$type,
					'remark'=>ijson_encode($remark),
					'createtime'=>TIMESTAMP,
					'status'=>$this->setting['is_jiesuan']?:0,
				);
				if(!$this->order['ordersn']){
					$new_commission['status']=1;
				}
				$this->insert('commission',$new_commission);
				//$this->model('notice')->notice_fenxiao_feeadd($new_commission['mid'],$new_commission['money']);
			}
			//判断是否存在区域代理
			$this->commission_order['isarea']=true;
			if($commission_level){
				$agent_update=array(
					'order_price +='=>$this->commission_order['order_price'],
					'order_num +='=>1,
					'commission_money +='=>$money,
				);
				$this->update('agent_area',$agent_update,array('id'=>$agent['id']));
			}
	}
	/*
		发展区域代理，推荐商户缴费
	*/
	function create_fee($order,$type=2){
		$fromuser=pdo_getcolumn('core_members',array('uniacid'=>$_SESSION['uniacid'],'id'=>$order['mid']),'fromuser');
		if($fromuser){
			$agent=$this->get('agent_area',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$fromuser));
			if($agent){
				$member=$this->get('member',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$agent['mid']));
			}
		}
		if(!$member || $member['stop']){
			return false;
		}
		if($type==2){
			$feename='rate_vip';
		}elseif($type==3){
			$feename='rate_merch';
		}elseif($type==4){
			$feename='rate_red';
		}
		if(strpos($agent['level_id'], "a")!== false){
			//获取默认等级佣金比例
			$default_level=$this->plugin_setting('default_level');
			$level_id=0;
			$commission_per=$default_level[$agent['level_id'].'_'.$feename];
		}elseif($agent['level_id']){
			$level=$this->get('level',array('id'=>$agent['level_id'],'uniacid'=>$_SESSION['uniacid']));
			$commission_per=$level[$feename];
		}
		if($order['fee']>0){
				if(substr($commission_per,-1)=='%'){
					$order_commission_money=($order['fee']*substr($commission_per,0,-1))/100;
				}else{
					$order_commission_money=$order['fee'];
				}
				$money=$order_commission_money;
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$agent['mid'],
					'agent_id'=>$agent['id'],
					'area_code'=>$agent['area_code'],
					'level'=>$agent['level_id'],
					'money'=>$money,
					'type'=>$type,
					'createtime'=>TIMESTAMP,
					'status'=>1,
				);
				$this->insert('commission',$new_commission);
		}
		return true;
	}
	/*
		订单完成时，把佣金状态由初始的订单待完成升级为待结算
	*/
	public function order_complete($order){
		$this->update('commission',array('status'=>1,'complete_time'=>TIMESTAMP),array('status'=>0,'ordersn'=>$order['ordersn']));
	}
	/*
		创建结算单
	*/
	public function create_balance($mid,$post=array()){
		if(!$mid){
			exi('请先选择要结算的会员！','error');
		}
		if(!$post['pay_type']){
			exi('请先选择支付方式！','error');
		}
		if($post['pay_type']=='downline'){
			if(!$post['wechat']){
				exi('请先填写微信号！','error');
			}
			if(!$post['mobile']){
				exi('请先填写联系电话！','error');
			}
		}
		if($post['pay_type']=='alipay'){
			if(!$post['realname']){
				exi('请先填写真实姓名！','error');
			}
			if(!$post['alipay']){
				exi('请先填写支付宝帐号！','error');
			}
			if(!$post['alipay1']){
				exi('请确认帐号','error');
			}
			if($post['alipay1']!=$post['alipay']){
				exi('确认帐号与支付宝帐号不匹配！','error');
			}
			$typetitle='支付宝';
		}
		if($post['pay_type']=='union'){
			if(!$post['realname']){
				exi('请输入姓名','error');
			}
			if(!$post['bankname']){
				exi('请输入所属银行','error');
			}
			if(!$post['bankcard']){
				exi('请银行卡号','error');
			}
			if(!$post['bankcard1']){
				exi('请确认卡号','error');
			}
			if($post['bankcard']!=$post['bankcard1']){
				exi('确认卡号与银行卡号不匹配！','error');
			}
			$typetitle='银行卡';
		}
		//获取可结算佣金
		$params=array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid,'status'=>1);
		$params['type']=array(2,4,7,8);
		if($this->setting['balance_day']){
			//结算天数
			$time=TIMESTAMP-intval($this->setting['balance_day'])*86400;
			$params['complete_time <']=$time;
		}
		$commissions=$this->getall('commission',$params);
		if(!$commissions){
			exi('没有可结算的佣金！','error');
		}
		$commission_num=count($commissions);
		$money=0;
		foreach($commissions as $commission){
			$money+=$commission['money'];
		}
		//结算最低佣金检测
		if($money<$this->setting['balance_money']){
			exi('可结算佣金太少，无法结算！','error');
		}
		$new_balance=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$mid,
			'balancesn'=>get_ordersn($this->tablename('commission'),'balancesn','AC'),
			'commission_num'=>$commission_num,
			'money'=>$money,
			'pay_type'=>$post['pay_type'],
			'realname'=>$post['realname'],
			'alipay'=>$post['alipay'],
			'bankname'=>$post['bankname'],
			'bankcard'=>$post['bankcard'],
			'wechat'=>$post['wechat'],
			'mobile'=>$post['mobile'],
			'createtime'=>TIMESTAMP,
			'status'=>$post['pay_type']=='credit' && $this->setting['balance_yue']?1:0,
		);
		//结算手续费
		if($this->setting['balance_per']){
			$new_balance['balance_pay']=intval($new_balance['money']*$this->setting['balance_per'])/100;
		}else{
			$new_balance['balance_pay']=0;
		}
		$new_balance['final_money']=$new_balance['money']-$new_balance['balance_pay'];
		$this->insert('balance',$new_balance);
		$balance_id=pdo_insertid();
		foreach($commissions as $commission){
			$update=array(
				'status'=>2,
				'balancesn'=>$new_balance['balancesn'],
			);
			$this->update('commission',$update,array('id'=>$commission['id']));
		}
		if($post['pay_type']=='credit'){
			$typetitle='余额';
			if($this->setting['balance_yue']){
				$this->pay_balance($balance_id,$post['pay_type']);
			}
		}
		if($post['pay_type']=='wechat'){
			$typetitle='微信';
		}
		$this->model('notice')->notice_fenxiao_tixian($mid,$money,$typetitle);
		return $balance_id;
	}
	/*
		商户交押金分红
	*/
	public function merch_yafee($yajin_log=array()){
		$merch=pdo_get('jy_merch_user',array('id'=>$yajin_log['merchid'],'uniacid'=>$_SESSION['uniacid']),array('pcd','address'));
		$address=array(
			'pcd'=>json_decode($merch['pcd'],true),
			'address'=>$merch['address']?:'无',
		);
		$order=array(
			'price'=>$yajin_log['fee'],
			'merchid'=>$yajin_log['merchid'],
			'mid'=>$yajin_log['mid'],
			'address'=>ijson_encode($address),
		);
		$this->create($order);
	}
	/*
		审核结算单
	*/
	public function check_balance($balance_id,$status,$remark=''){
		$update=array(
			'status'=>$status,
			'check_time'=>TIMESTAMP,
			'remark'=>$remark,
		);
		$this->update('balance',$update,array('id'=>$balance_id));
	}
	/*
		打款结算单
	*/
	public function pay_balance($balance_id,$pay_type){
		$balance=$this->get('balance',array('id'=>$balance_id,'uniacid'=>$_SESSION['uniacid']));
		if(!$balance || $balance['status']!=1){
			exi('结算单不存在或者不符合打款条件，打款失败！','error');
		}
		$pay_types=array_keys($this->pay_types);
		if(!$pay_type || !in_array($pay_type,$pay_types)){
			exi('未设置打款方式或者打款方式不合法，打款失败！','error');
		}
		$func_name='pay_balance_by_'.$pay_type;
		$trade_no=$this->$func_name($balance['mid'],$balance['final_money'],$balance['balancesn'],$balance['merchid']);
		$update=array(
			'status'=>3,
			'pay_type'=>$pay_type,
			'pay_trade_no'=>$trade_no,
			'pay_time'=>TIMESTAMP,
		);
		$this->update('balance',$update,array('id'=>$balance['id']));
		$this->model('notice')->notice_fenxiao_dakuan($balance['mid'],$balance['final_money']);
		return true;
	}
	/*
		打款到余额
	*/
	protected function pay_balance_by_credit($mid,$money,$balancesn){
		return cfc('core')->member_credit($mid,'credit2',$money,true,$this->plugin_name,$remark='分销佣金打款');
	}
	/*
		打款到微信零钱
	*/
	protected function pay_balance_by_wechat($mid,$money,$balancesn,$merchid=0){
		if(!$merchid){
			exi('商户不支持打款到微信零钱，打款失败！','error');
		}
		$params=array(
			'openid'=>$mid,
			'mch_billno'=>$balancesn,
			'money'=>$money,
			'remark'=>'代理商佣金发放',
		);
		$res=cfc('wechat_pay')->mch_pay($params);
		return $res['payment_no'];
	}
	/*
		打款到支付宝
	*/
	protected function pay_balance_by_alipay($mid,$money,$balancesn){
		return true;
		exi('暂不支持打款到支付宝！','error');
	}
	/*
		打款到银行账户
	*/
	protected function pay_balance_by_union($mid,$money,$balancesn){
		return true;
		exi('暂不支持打款到银行账户！','error');
	}

	public function commission_remark($remark){
		if(!$remark){
			return '';
		}
		$remark=json_decode($remark,true);
		$goods_str='';
		if($remark['goods_commission']){
			foreach($remark['goods_commission'] as $goods){
				$goods['title']=pdo_getcolumn('jy_weishop_goods',array('id'=>$goods['goods_id']),'title');
				$goods_str.="商品ID【{$goods['goods_id']}】，商品名称【{$goods['title']}】，商品数量【{$goods['total']}】，商品总价【{$goods['total_price']}】，佣金规则【{$goods['commission_per']}】，分销佣金【{$goods['commission_money']}】\n";
			}
		}else{
			$goods_str='';
		}
		$remark['level_title']=pdo_getcolumn('jy_area_psi_level',array('uniacid'=>$_SESSION['uniacid'],'level'=>$remark['level_id']),'title');
		$remark['level_title']=$remark['level_title']?:'默认等级';
		$remark_str=<<<TPL
分销商等级ID【{$remark['level_id']}】，等级名称【{$remark['level_title']}】，佣金等级【{$remark['commission_level']}】，订单总价【{$remark['order_price']}】
商品独立佣金：
{$goods_str}
订单佣金：
除去设置独立佣金的商品外订单金额【{$remark['order_commission']['order_price']}】，佣金规则【{$remark['order_commission']['commission_per']}%】，分销佣金【{$remark['order_commission']['commission_money']}】
佣金总计：【{$remark['commission_money']}】
TPL;
		return $remark_str;
	}
}